package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.bean.UserAnswerNumbean;
import com.atguigu.realtime.utils.ClickHouseUtil;
import com.atguigu.realtime.utils.DateFormatUtil;
import com.atguigu.realtime.utils.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;

public class DwsCorrectAnswerCt {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */
        //todo 3 从kafka读取 dwd_test_exam_question
        String topicName = "dwd_test_exam_question";
        String GroupID = "dws_correct_answer_ct";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, GroupID));

        //todo 4 转换结构

        SingleOutputStreamOperator<UserAnswerNumbean> mapStream = streamSource.map(new MapFunction<String, UserAnswerNumbean>() {
            @Override
            public UserAnswerNumbean map(String value) throws Exception {
                JSONObject obj = JSON.parseObject(value);
                ArrayList<String> isCorrectList = new ArrayList<>();
                ArrayList<String> answerList = new ArrayList<>();

                HashSet<String> answerCorrectUvSet = new HashSet<>();
                HashSet<String> answerUvSet = new HashSet<>();
                if ("1".equals(obj.getString("is_correct"))) {
                    isCorrectList.add(obj.getString("word"));
                    answerCorrectUvSet.add(obj.getString("user_id"));
                }
                answerList.add(obj.getString("word"));
                answerUvSet.add(obj.getString("user_id"));
                return UserAnswerNumbean
                        .builder()
                        .questionId(obj.getString("question_id"))
                        .userId(obj.getString("user_id"))
                        .isCorrect(obj.getString("is_correct"))

                        //正确答题次数集合
                        .answerCorrectCtList(isCorrectList)
                        //答题次数集合
                        .answerNumCtList(answerList)
                        .answerCorrectUvSet(answerCorrectUvSet)
                        .answerUvSet(answerUvSet)
                        .ts(obj.getLong("ts") * 1000)
                        .build();
            }
        });
        //todo 5 开窗聚合
        //水位线
        SingleOutputStreamOperator<UserAnswerNumbean> watermarks = mapStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<UserAnswerNumbean>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<UserAnswerNumbean>() {
                    @Override
                    public long extractTimestamp(UserAnswerNumbean element, long recordTimestamp) {
                        return element.getTs();
                    }
                }));
        //分组，开窗，聚合
        SingleOutputStreamOperator<UserAnswerNumbean> resultStream = watermarks.keyBy(UserAnswerNumbean::getQuestionId)
                .window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<UserAnswerNumbean>() {
                    @Override
                    public UserAnswerNumbean reduce(UserAnswerNumbean value1, UserAnswerNumbean value2) throws Exception {
                        value1.setAnswerCorrectCtList(value2.getAnswerCorrectCtList());
                        value1.setAnswerNumCtList(value2.getAnswerNumCtList());
                        value1.setAnswerCorrectUvSet(value2.getAnswerCorrectUvSet());
                        value1.setAnswerUvSet(value2.getAnswerUvSet());
                        return value1;
                    }
                }, new WindowFunction<UserAnswerNumbean, UserAnswerNumbean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<UserAnswerNumbean> input, Collector<UserAnswerNumbean> out) throws Exception {

                        UserAnswerNumbean bean = input.iterator().next();
                        int answerCorrectCt = bean.getAnswerCorrectCtList().size();
                        int answerNumCt = bean.getAnswerNumCtList().size();
                        int UvCt = bean.getAnswerUvSet().size();
                        int correctUvCt = bean.getAnswerCorrectUvSet().size();
                        double accuracy = answerCorrectCt * 1.0 / answerNumCt;
                        double correctUserPercentage = correctUvCt * 1.0 / UvCt;
                        bean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        bean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        bean.setAnswerCorrectCt(answerCorrectCt);
                        bean.setAnswerNumCt(answerNumCt);
                        bean.setAccuracy(accuracy);
                        bean.setAnswerCorrectUv(correctUvCt);
                        bean.setAnswerUv(UvCt);
                        bean.setAnswerCorrectUserPercentage(correctUserPercentage);
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                });

        resultStream.print();
        //写入到click house
        resultStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_correct_answer_ct values(?,?,?,?,?,?,?,?,?,?,?,?)"));


        //执行
        env.execute();

    }
}
